//
//  HWGameLiveRoomController.swift
//  PlayWithProject
//
//  Created by 王昌健 on 2021/10/15.
//

import UIKit
import TXLiteAVSDK_Professional

import SwiftyGif
import IQKeyboardManagerSwift
class HWGameLiveRoomController: HWBaseViewController {
    
    var liveModel:HWVoiceRoomInfoModel?
    
    var statusBarBgView:UIView!
    /// 播放器父视图
    var playerFatherView:UIView!
    /// 播放器
    lazy var playerView: SuperPlayerView = {
        let playerView = SuperPlayerView()
        playerView.fatherView = self.playerFatherView
        playerView.delegate = self
        return playerView
    }()
    //    var playerView:SuperPlayerView!
    
    //    override var style: UIStatusBarStyle = .lightContent
    
    //    var style:UIStatusBarStyle = .lightContent
    
    
    //    override var preferredStatusBarStyle: UIStatusBarStyle{
    //        return .lightContent
    //
    //    }
    
    var httpManager = HWGameLiveHttpManager()
    //    let httpManager = HWHttpManager()
    var chatBaseView = HWGameLiveChatBaseView()
    var chatFieldView:HWVoiceRoomChatFieldView!
    
    /// 礼物
    var giftView = HWVoiceRoomGiftView()
    
    var hotLabel:UILabel = HWLabel.createBoldLabel(title: "", color: "#FFFFFF", font: 10*widthScale)
    
    var msgModelArr = NSMutableArray() as! [HWGameLiveChatModel]
    
    var svgplayer = SVGAPlayer.init()
    var parser = SVGAParser.init()
    var rePlayVideo = false
    var closeCallBack:(()->())?
    
}

extension HWGameLiveRoomController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        playVideo()
        
        addAction()
        
        loadData()
        
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        let _ = super.preferredStatusBarStyle
        return .lightContent
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        //        self.navigationController?.isNavigationBarHidden = true
        UIApplication.shared.statusBarStyle = .lightContent
        if self.rePlayVideo == true {
            self.playVideo()
            self.rePlayVideo = false
        }
        
        //        UINavigationBar.appearance().barStyle = .default
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = false
        if #available(iOS 13.0, *) {
            UIApplication.shared.statusBarStyle = .darkContent
        } else {
            UIApplication.shared.statusBarStyle = .default
        }
        self.playerView.pause()
        self.playerView.resetPlayer()
        
        if #available(iOS 15.0, *)  {
            let appearance = UITabBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundImage = UIImage()
            appearance.shadowImage = UIColor.createImageWithColor(color: .white)
            UITabBar.appearance().standardAppearance = appearance
            UITabBar.appearance().scrollEdgeAppearance = appearance
            UITabBar.appearance().tintColor = UIColor.colorWithHexString(hexString: "#FFB60A")
            UITabBar.appearance().layer.shadowColor = UIColor.colorWithAlphaHexString(hexString: "#C4C4C4", alpha: 0.16).cgColor
            UITabBar.appearance().layer.shadowOffset = CGSize(width: 0, height: -3)
            UITabBar.appearance().layer.shadowOpacity = 1
            UITabBar.appearance().layer.shadowRadius = 6
        }
    }
}

extension HWGameLiveRoomController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        //        self.style = .lightContent
        statusBarBgView = UIView()
        statusBarBgView.backgroundColor = .black
        view.addSubview(statusBarBgView)
        
        playerFatherView = UIView()
        playerFatherView.backgroundColor = .black
        view.addSubview(playerFatherView)
        self.playerView.fatherView = self.playerFatherView;
        
        view.addSubview(chatBaseView)
        
        chatFieldView = HWVoiceRoomChatFieldView()
        view.addSubview(chatFieldView)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotify1(_:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
        HWGameLiveImManager.shared.delegate = self
        
        self.giftView.topView.isHidden = true
        let seatModel = HWVoiceRoomSeatModel()
        //        seatModel.seatUser
        seatModel.seatUser = HWVoiceRoomUserInfo()
        seatModel.seatUser?.userId = self.liveModel?.ownerId
        
        self.giftView.sendToUsers = [seatModel]
        
        chatBaseView.liveInfoModel = self.liveModel
        
        view.addSubview(svgplayer)
        view.sendSubviewToBack(svgplayer)
        
        svgplayer.delegate = self
    }
    
    private func initFrame() -> Void {
        
        statusBarBgView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(44*widthScale)
        }
        
        self.playerFatherView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(statusBarBgView.snp.bottom)
            make.height.equalTo(self.playerFatherView.snp.width).multipliedBy(9.0 / 16.0)
        }
        
        chatBaseView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(self.playerFatherView.snp.bottom)
        }
        
        chatFieldView.snp.makeConstraints { make in
            make.top.equalTo(self.view.snp.bottom)
            make.height.equalTo(50*widthScale)
            make.left.right.equalTo(0)
        }
        
        svgplayer.snp.makeConstraints { make in
            make.left.right.top.bottom.equalTo(0)
        }
    }
    
    func playVideo() -> Void {
        let playerModel = SuperPlayerModel()
        playerModel.videoURL = self.liveModel?.play_url
        self.playerView.controlView.title = self.liveModel?.name
        self.playerView.disableGesture = true
        //        self.playerView.playerConfig.renderMode = 1
        let dv = self.playerView.controlView as! SPDefaultControlView
        dv.videoSlider.isHidden = true
        dv.totalTimeLabel.isHidden = true
        dv.currentTimeLabel.isHidden = true
        //        dv.danmakuBtn.isHidden = true
        dv.disableDanmakuBtn = true
        let hotImageView = UIImageView()
        hotImageView.image = UIImage(named: "gameLiveHotImage")
        dv.addSubview(hotImageView)
        hotImageView.snp.makeConstraints { make in
            make.left.equalTo(dv.titleLabel)
            make.top.equalTo(dv.titleLabel.snp.bottom).offset(3*widthScale)
            make.width.equalTo(8*widthScale)
            make.height.equalTo(10*widthScale)
        }
        hotLabel.text = liveModel?.hot
        dv.addSubview(hotLabel)
        hotLabel.snp.makeConstraints { make in
            make.left.equalTo(hotImageView.snp.right).offset(2*widthScale)
            make.centerY.equalTo(hotImageView)
        }

        //        let v = UIView()
        //        v.backgroundColor = .red
        //        dv.addSubview(v)
        //        v.snp.makeConstraints { make in
        //            make.right.bottom.equalTo(-50)
        //            make.width.equalTo(100)
        //            make.height.equalTo(40)
        //        }
        
        self.playerView.play(with: playerModel)
        
    }
}

extension HWGameLiveRoomController {
    @objc func keyboardWillChangeFrameNotify1(_ notify:NSNotification) -> Void {
        let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let transformY = keyboardFrame.origin.y - self.view.frame.size.height;
        UIView.animate(withDuration: duration) {
            
            
            
        }
        UIView.animate(withDuration: duration) {
            if transformY == 0.0 {
                self.chatFieldView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                
            }else{
                self.chatFieldView.transform = CGAffineTransform.init(translationX: 0, y: transformY-50*widthScale)
            }
        } completion: { done in
            
            //            self.setPassword.isHide = {
            //                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            //                    self.chatFieldView.isHidden = false
            //                }
            //            }
            
        }
        
        
    }
    
    func addAction() -> Void {
        /// 聊天
        self.chatBaseView.chatButtonClick = {
            self.chatFieldView.textField.becomeFirstResponder()
        }
        /// 管理
        self.chatBaseView.managerButtonClick = {
            
        }
        /// 送礼物
        self.chatBaseView.giftButtonClick = {
            
            self.giftView.show()
        }
        /// 跳转游戏
        self.chatBaseView.downLoadButtonClick = {
            mod in
            self.rePlayVideo = true
            let gameDetail = HWGameDetailController()
            gameDetail.gameId = mod.id
            self.navigationController?.pushViewController(gameDetail, animated: true)
        }
        
        self.chatBaseView.followButtonClick = {
            self.httpManager.getLiveFollow(roomId:self.liveModel?.room_id ?? "") { message in
                self.httpManager.getGameLiveRoomInfo(roomId: self.liveModel?.room_id ?? "") { roomInfo in
                    self.chatBaseView.liveInfoModel = roomInfo
                } failure: { error in
                    
                }
                
            } failure: { error in
                
            }
            
        }
        
        giftView.rechargeButtonClick = {
            url in
            self.giftView.hide()
            self.rePlayVideo = true
            let webController = HWWebController()
            webController.urlString = url
            self.navigationController?.pushViewController(webController, animated: true)
        }
        
        ///送礼物
        giftView.sendGift = {
            
            users,giftModel,num in
            var type = "0"
            if giftModel.img_type == 1 {
                type = "1"
            }
            if giftModel.img_type == 2 {
                type = "2"
            }
            var userIds = ""
            
            for user in users {
                userIds.append(user.seatUser?.userId ?? "")
                userIds.append(",")
            }
            userIds.removeLast()
            self.httpManager.sendGift(roomId: self.liveModel?.room_id ?? "", id: giftModel.id, uids: userIds,num: num) { message in
                let str = "playwith#gift#" + type + "#"
                let sendText = str + (type == "0" ? giftModel.icon : giftModel.img) + "#" + giftModel.time
                HWGameLiveImManager.shared.sendRoomTextMessage(text: sendText) { code, message in
                    if code == 0 {
                        var  str = "playwith#giftName#送 " + giftModel.name
                        str = str  + " x" + num
                        HWGameLiveImManager.shared.sendRoomTextMessage(text: str) { code, message in
                            if code == 0 {
                                let userInfo = HWGameLiveChatModel()
                                userInfo.userName = HWLocallyStoredData.getUserName()
                                userInfo.userFace = HWLocallyStoredData.getUserFace()
                                userInfo.userId = HWLocallyStoredData.getLoginUserID()
                                userInfo.msgType = .send
                                userInfo.text = String(str.suffix(str.count-18))
                                
                                self.msgModelArr.append(userInfo)
                                //                                self.chatView.msgDataArr = self.msgModelArr
                                self.chatBaseView.chatModelArr = self.msgModelArr
                                self.giftView.loadData()
                                if type == "1" {
                                    let image = UIImageView.init(gifURL: URL(string: giftModel.img)!, manager: .defaultManager, loopCount: 5)
                                    image.frame = self.view.bounds
                                    self.view.addSubview(image)
                                    
                                    //                                image.setGifFromURL(URL(string: giftModel.img)!)
                                    image.delegate = self
                                    image.startAnimatingGif()
                                    
                                    
                                }else if type == "2" {
                                    self.parser.parse(with: URL(string: giftModel.img)!) { videoItem in
                                        self.svgplayer.videoItem = videoItem
                                        self.svgplayer.loops = 1
                                        self.svgplayer.clearsAfterStop = true
                                        self.view.bringSubviewToFront(self.svgplayer)
                                        self.svgplayer.startAnimation()
                                    } failureBlock: { error in
                                        
                                    }
                                    
                                }else{
                                    
                                }
                                
                                
                            }
                        }
                    }
                }
            } failure: { error in
                self.view.showHUD(title: error)
            }
            
        }
        
        self.chatFieldView.sendText = {
            text in
            let model = HWGameLiveChatModel()
            model.text = text
            model.userName = HWLocallyStoredData.getUserName()
            self.msgModelArr.append(model)
            self.chatBaseView.chatModelArr = self.msgModelArr
            self.chatFieldView.textField.text = ""
            self.chatFieldView.textField.resignFirstResponder()
            HWGameLiveImManager.shared.sendRoomTextMessage(text: text) { code, message in
                
            }
        }
    }
}
//数据相关
extension HWGameLiveRoomController{
    
    func loadData() -> Void {
        httpManager.getGiftList(roomId: liveModel?.room_id ?? "") { models in
            self.giftView.giftModels = models
        } failure: { error in
            
        }
        
    }
    
}
extension HWGameLiveRoomController :SuperPlayerDelegate{
    func superPlayerBackAction(_ player: SuperPlayerView!) {
        self.navigationController?.popViewController(animated: true)
    }
    func superPlayerDidEnd(_ player: SuperPlayerView!) {
        print("结束")
    }
    
    func superPlayerError(_ player: SuperPlayerView!, errCode code: Int32, errMessage why: String!) {
        print(why ?? "播放出错了")
        self.playerView.resetPlayer()
    }
}

extension HWGameLiveRoomController: HWLiveIMDelegate {
    func userEnterRoom(userModel: HWGameLiveChatModel) {
        self.msgModelArr.append(userModel)
        self.chatBaseView.chatModelArr = self.msgModelArr
    }
    
    func userLeaveRoom(userModel: HWGameLiveChatModel) {
        
    }
    
    func receiveGroupText(userModel: HWGameLiveChatModel) {
        
        if userModel.text.hasPrefix("playwith#giftName#") {
            let str = userModel.text.suffix(userModel.text.count-18)
            userModel.text = String(str)
            self.msgModelArr.append(userModel)
            self.chatBaseView.chatModelArr = self.msgModelArr
        }else if userModel.text.contains("playwith#gift#"){
            let arr : Array = userModel.text.components(separatedBy: "#")
            if arr[2] == "1" {
                let image = UIImageView.init(gifURL: URL(string: arr[3])!, manager: .defaultManager, loopCount: 5)
                image.frame = self.view.bounds
                self.view.addSubview(image)
                
                //                                image.setGifFromURL(URlL(string: giftModel.img)!)
                image.delegate = self
                image.startAnimatingGif()
            }else if arr[2] == "2" {
                self.parser.parse(with: URL(string: arr[3])!) { videoItem in
                    self.svgplayer.videoItem = videoItem
                    self.svgplayer.loops = 1
                    self.svgplayer.clearsAfterStop = true
                    self.view.bringSubviewToFront(self.svgplayer)
                    self.svgplayer.startAnimation()
                } failureBlock: { error in
                    
                }
                
            }else{
                
            }
            
        }else{
            self.msgModelArr.append(userModel)
            self.chatBaseView.chatModelArr = self.msgModelArr
        }
        
        //        self.msgModelArr.append(userModel)
        //        self.chatBaseView.chatModelArr = self.msgModelArr
    }
    
    func receiveGroupCustomMessage(typeDic: NSDictionary) {
        
        if typeDic["type"] as! String == "close" {
            view.showHUD(title: "主播已关闭直播间")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                
                self.navigationController?.popViewController(animated: true)
                self.closeCallBack?()
            }
        }
    }
    
    
}
extension HWGameLiveRoomController:SVGAPlayerDelegate {
    func svgaPlayerDidFinishedAnimation(_ player: SVGAPlayer!) {
        self.view.sendSubviewToBack(self.svgplayer)
    }
}
extension HWGameLiveRoomController:SwiftyGifDelegate{
    func gifDidStop(sender: UIImageView) {
        sender.removeFromSuperview()
    }
}
